//
//  GSDKUserLoginView.m
//  GameSDK
//
//  Created by Johnny on 2017/8/2.
//  Copyright © 2017年 Johnny. All rights reserved.
//

#import "GSDKUserLoginView.h"
#import "GSDKUserAccountModel.h"
#import "GSDKUserLoginHistoryView.h"
#import "GSDKCommonMethod.h"
#import "YYKit.h"
#import "GSDKUserConfig.h"
@interface GSDKUserLoginView () <UITextFieldDelegate>
@property (nonatomic) BOOL isShowHistoryView;
@property (nonatomic,strong) UIImageView * logoImageView;
@property (nonatomic,strong) UIView * contentView;
@property (nonatomic,strong) UIImageView * contentBgView;
@property (nonatomic,strong) UIImageView * contentLineView;
@property (nonatomic,strong) UITextField * unTextField;
@property (nonatomic,strong) UITextField * pwTextField;
@property (nonatomic,strong) UIButton * historyButton;
@property (nonatomic,strong) UIButton * loginButton;
@property (nonatomic,strong) UIButton * forgotPWButton;
@property (nonatomic,strong) GSDKUserLoginHistoryView * loginHistoryView;
@property (nonatomic,strong) UILabel * errorLabel;
@property (nonatomic,strong) UIButton * backButton;
@property (nonatomic,strong) UIButton * cancelButton;
@property (nonatomic,strong) NSDictionary * titleLabelDic;
@property (nonatomic,strong) NSArray<GSDKUserAccountModel *>* accounts;
@end

@implementation GSDKUserLoginView
- (void)dealloc {
    DEBUGMSG(@"GSDKUserLoginView dealloc");
}

- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    [self hideError];
}

- (id)init {
    self = [super init];
    if (self != nil) {
        _isShowHistoryView = false;
        
        [self setupUI];
        [self operationUI];
    }
    return self;
}

- (void)reloadAt:(GSDKUserLoginViewModel*)viewModel {
    _unTextField.text = viewModel.userName;
    _pwTextField.text = viewModel.passWord;
    
    self.accounts = viewModel.userHistorys;
    
    NSMutableArray<GSDKUserLoginHistoryViewModel*>* viewModels = [NSMutableArray new];
    
    for (GSDKUserAccountModel * model in viewModel.userHistorys) {
        [viewModels addObject:[GSDKUserLoginHistoryViewModel getViewModel:model]];
    }
    
    [_loginHistoryView reloadView:viewModels];
    [self textChangeAction];
}

- (void)errorAt:(GSDKUserErrorViewModel*)viewModel {
    if (UserViewWidth < 320) {
        [GSDKMessagePopView showAt:viewModel.errorString andBGColor: [UIColor colorWithHexString:@"#e82929"]];
    } else {
        [self showErrorAtMsg:viewModel.errorString];
    }
}

#pragma mark - setupUI
- (void)setupUI {
    self.backgroundColor = [UIColor whiteColor];
    self.layer.cornerRadius = 4;
    
    _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backButton setTitle:[NSString stringWithFormat:@" %@", [NSString localizedStringForKey:@"GSDK_back_text" value:@"返回"]] forState:UIControlStateNormal];
    [_backButton setTitleColor:[UIColor colorWithHexString:@"#b9b9b9"] forState:UIControlStateNormal];
    _backButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [_backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [_backButton setImage:[UIImage imageNamed:@"ZYSDK_Resourcres.bundle/pic/left"] forState:UIControlStateNormal];
    _backButton.frame = CGRectMake(10, 8, 50, 30);
    [self addSubview:_backButton];
    
    _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_cancelButton addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
    [_cancelButton setImage:[UIImage imageNamed:@"GtSDK_Resourcres.bundle/pic/close"] forState:UIControlStateNormal];
    _cancelButton.frame = CGRectMake(UserViewWidth - 40, 10, 30, 30);
    [self addSubview:_cancelButton];
    
    _logoImageView = [[UIImageView alloc]init];
    _logoImageView.image = [UIImage imageNamed:@"ZYSDK_Resourcres.bundle/pic/newLogo"];
    _logoImageView.frame = CGRectMake(UserViewWidth/2 - 119.7/2, 15, 119.7, 35);
    [self addSubview:_logoImageView];
    
    _errorLabel = [[UILabel alloc]init];
    _errorLabel.font = [UIFont systemFontOfSize:10];
    _errorLabel.hidden = YES;
    _errorLabel.alpha = 0.5;
    _errorLabel.textAlignment = NSTextAlignmentCenter;
    _errorLabel.textColor = [UIColor colorWithHexString:@"#ff6b02"];
    _errorLabel.backgroundColor = [UIColor clearColor];
    [self addSubview:_errorLabel];
    _errorLabel.layer.borderColor = [UIColor colorWithHexString:@"#ff6b02"].CGColor;
    _errorLabel.layer.borderWidth = 0.5;
    _errorLabel.layer.cornerRadius = 4;
    
    [self setupContent];
    
    _loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _loginButton.frame = CGRectMake(_contentView.frame.origin.x, _contentView.frame.origin.y + _contentView.frame.size.height + 10, _contentView.frame.size.width, 36);
    [_loginButton setBackgroundImage:[[UIImage imageNamed:@"ZYSDK_Resourcres.bundle/pic/btn_normal"] stretchableImageWithLeftCapWidth:10 topCapHeight:10] forState:UIControlStateNormal];
    [_loginButton setBackgroundImage:[[UIImage imageNamed:@"ZYSDK_Resourcres.bundle/pic/btn_selectd"] stretchableImageWithLeftCapWidth:10 topCapHeight:10] forState:UIControlStateSelected];
    _loginButton.adjustsImageWhenHighlighted = NO;
    _loginButton.titleLabel.font = [UIFont systemFontOfSize:14.5];
    [_loginButton setTitle: [NSString localizedStringForKey:@"GSDK_login_text" value:@"登 录"] forState:UIControlStateNormal];
    [_loginButton addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_loginButton];
    
    NSString * forgotText = [NSString stringWithFormat:@" %@", [NSString localizedStringForKey:@"GSDK_fotgotpd_text" value:@"忘记密码"]];
    CGSize forgotSize = [forgotText sizeWithFont:[UIFont systemFontOfSize:13]
                           constrainedToSize:CGSizeMake(UserViewWidth, 24) lineBreakMode:NSLineBreakByWordWrapping];
    
    _forgotPWButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _forgotPWButton.frame = CGRectMake(UserViewWidth - (28 + forgotSize.width) - _contentView.frame.origin.x, _loginButton.frame.origin.y + _loginButton.frame.size.height + 5, 28 + forgotSize.width, 24);
    _forgotPWButton.titleLabel.font = [UIFont systemFontOfSize:13];
    [_forgotPWButton setTitleColor:[UIColor colorWithHexString:@"#777777"] forState:UIControlStateNormal];
    [_forgotPWButton setImage:[UIImage imageNamed:@"ZYSDK_Resourcres.bundle/pic/icon_forgotPW"] forState:UIControlStateNormal];
    [_forgotPWButton addTarget:self action:@selector(forgotAction) forControlEvents:UIControlEventTouchUpInside];
    [_forgotPWButton setTitle:forgotText forState:UIControlStateNormal];
    [self addSubview:_forgotPWButton];
    
    _loginHistoryView = [[GSDKUserLoginHistoryView alloc]initWithFrame:CGRectMake(_contentView.frame.origin.x, _contentView.frame.origin.y + _contentView.frame.size.height/2, _contentView.frame.size.width, 0) style:UITableViewStylePlain];
    [self addSubview:_loginHistoryView];
}

- (void)setupContent {
    _contentView = [[UIView alloc]init];
    if (UserViewWidth < 320) {
        _contentView.frame = CGRectMake(10, _logoImageView.frame.size.height + _logoImageView.frame.origin.y + 20, UserViewWidth - 10*2, 88);
    } else {
        _contentView.frame = CGRectMake(30, _logoImageView.frame.size.height + _logoImageView.frame.origin.y + 20, UserViewWidth - 30*2, 88);
    }
    [self addSubview:_contentView];
    
    _contentBgView = [[UIImageView alloc]init];
    _contentBgView.frame = CGRectMake(0, 0, _contentView.frame.size.width, _contentView.frame.size.height);
    [_contentView addSubview:_contentBgView];
    _contentBgView.layer.cornerRadius = 4;
    _contentBgView.layer.borderWidth = 0.5;
    _contentBgView.layer.borderColor = [UIColor colorWithHexString:@"#e4e4e4"].CGColor;
    
    _contentLineView = [[UIImageView alloc]init];
    _contentLineView.backgroundColor = [UIColor colorWithHexString:@"#e4e4e4"];
    _contentLineView.frame = CGRectMake(0, _contentView.frame.size.height/2, _contentView.frame.size.width, 0.5);
    [_contentView addSubview:_contentLineView];
    
    UIImageView * iconImageView = [[UIImageView alloc]init];
    iconImageView.image = [UIImage imageNamed:@"ZYSDK_Resourcres.bundle/pic/icon_user"];
    iconImageView.frame = CGRectMake(10, _contentView.frame.size.height/2/2 - 22/2, 22, 22);
    [_contentView addSubview:iconImageView];
    iconImageView = [[UIImageView alloc]init];
    iconImageView.image = [UIImage imageNamed:@"ZYSDK_Resourcres.bundle/pic/icon_pw"];
    iconImageView.frame = CGRectMake(10, _contentView.frame.size.height/2 + _contentView.frame.size.height/2/2 - 22/2, 22, 22);
    [_contentView addSubview:iconImageView];
    
    _historyButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _historyButton.frame = CGRectMake(_contentView.frame.size.width - 10 - 24, _contentView.frame.size.height/2/2 - 24/2, 24, 24);
    [_historyButton setImage:[UIImage imageNamed:@"ZYSDK_Resourcres.bundle/pic/icon_userHitory"] forState:UIControlStateNormal];
    [_historyButton addTarget:self action:@selector(historyAction) forControlEvents:UIControlEventTouchUpInside];
    [_contentView addSubview:_historyButton];
    
    _unTextField = [[UITextField alloc]init];
    _unTextField.frame = CGRectMake(iconImageView.frame.origin.x * 2 + iconImageView.frame.size.width, 0, _contentView.frame.size.width - ((iconImageView.frame.origin.x * 2 + iconImageView.frame.size.width) + (_contentView.frame.size.width - _historyButton.frame.origin.x + _contentView.frame.size.width - _historyButton.frame.origin.x - _historyButton.frame.size.width)), 44);
    _unTextField.placeholder = [NSString localizedStringForKey:@"GSDK_username_placeholaer" value: @"用户名/邮箱"];
    _unTextField.returnKeyType = UIReturnKeyNext;
    _unTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _unTextField.delegate = self;
    _unTextField.clearButtonMode = UITextFieldViewModeAlways;
    _unTextField.keyboardType = UIKeyboardTypeEmailAddress;
    _unTextField.autocorrectionType = UITextAutocorrectionTypeNo;
    _unTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    [_unTextField addTarget:self action:@selector(textChangeAction) forControlEvents:UIControlEventEditingChanged];
    _unTextField.font = [UIFont systemFontOfSize:13];
    [_contentView addSubview:_unTextField];
    
    _pwTextField = [[UITextField alloc]init];
    _pwTextField.frame = CGRectMake(iconImageView.frame.origin.x * 2 + iconImageView.frame.size.width, _contentView.frame.size.height/2, _contentView.frame.size.width - ((iconImageView.frame.origin.x * 2 + iconImageView.frame.size.width) + 10), 44);
    _pwTextField.placeholder = [NSString localizedStringForKey:@"GSDK_password_placeholaer" value: @"6-12位字母、数字和下划线"];
    _pwTextField.returnKeyType = UIReturnKeyGo;
    _pwTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _pwTextField.delegate = self;
    _pwTextField.keyboardType = YES;
    _pwTextField.secureTextEntry = YES;
    _pwTextField.clearButtonMode = UITextFieldViewModeAlways;
    _pwTextField.keyboardType = UIKeyboardTypeEmailAddress;
    _pwTextField.autocorrectionType = UITextAutocorrectionTypeNo;
    _pwTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    [_pwTextField addTarget:self action:@selector(textChangeAction) forControlEvents:UIControlEventEditingChanged];
    _pwTextField.font = [UIFont systemFontOfSize:13];
    [_contentView addSubview:_pwTextField];
}

#pragma mark - Error
- (void)showErrorAtMsg:(NSString*)msgString {
    _errorLabel.hidden = NO;
    _errorLabel.text = msgString;
    CGSize msgSize = [msgString sizeWithFont:_errorLabel.font
                           constrainedToSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) lineBreakMode:_errorLabel.lineBreakMode];
    _errorLabel.frame = CGRectMake((_contentView.frame.origin.x + _contentView.frame.size.width) - (msgSize.width + 8), _logoImageView.frame.size.height + _logoImageView.frame.origin.y, msgSize.width + 8, 16);
    
    _contentBgView.layer.borderColor = [UIColor colorWithHexString:@"#ff6b02"].CGColor;
    _contentLineView.backgroundColor = [UIColor colorWithHexString:@"#ff6b02"];
}

- (void)hideError {
    _errorLabel.hidden = YES;
    _contentBgView.layer.borderColor = [UIColor colorWithHexString:@"#e4e4e4"].CGColor;
    _contentLineView.backgroundColor = [UIColor colorWithHexString:@"#e4e4e4"];
}

#pragma mark - operationUI
- (void)operationUI {
    __weak GSDKUserLoginView * bSelf = self;
    _loginHistoryView.selectUserBlock = ^(int index) {
        [bSelf hideHistoryView];
        GSDKUserAccountModel * account = bSelf.accounts[index];
        bSelf.unTextField.text = account.userName;
        bSelf.pwTextField.text = account.passWord;
        [bSelf textChangeAction];
    };
}

- (void)showHistoryView {
    _isShowHistoryView = YES;
    _loginHistoryView.selectedString = _unTextField.text;
    [_loginHistoryView reloadData];
    [self hideError];
    __weak GSDKUserLoginView * bSelf = self;
    [UIView animateWithDuration:0.35 animations:^{
        bSelf.loginHistoryView.frame = CGRectMake(bSelf.loginHistoryView.frame.origin.x, bSelf.loginHistoryView.frame.origin.y, bSelf.loginHistoryView.frame.size.width, 44 * 3);
        bSelf.historyButton.transform = CGAffineTransformMakeRotation(M_PI);
    } completion:^(BOOL finished) { }];
}

- (void)hideHistoryView {
    _isShowHistoryView = NO;
    __weak GSDKUserLoginView * bSelf = self;
    [UIView animateWithDuration:0.35 animations:^{
        bSelf.loginHistoryView.frame = CGRectMake(bSelf.loginHistoryView.frame.origin.x, bSelf.loginHistoryView.frame.origin.y, bSelf.loginHistoryView.frame.size.width, 0);
        bSelf.historyButton.transform = CGAffineTransformMakeRotation(0);
    } completion:^(BOOL finished) { }];
}

#pragma mark - Action
- (void)backAction {
    if (_backBlock) {
        _backBlock();
    }
}

- (void)historyAction {
    if (_isShowHistoryView) {
        [self hideHistoryView];
    } else {
        [self showHistoryView];
    }
}

- (void)loginAction {
    if (_loginBlock && _unTextField.text.length > 0 && _pwTextField.text.length > 0) {
        _loginBlock(_unTextField.text,_pwTextField.text,false);
    }
}

- (void)serviceAction {
    
}

- (void)forgotAction {
    if (_forgotBlock) {
        _forgotBlock();
    }
}

- (void)cancelAction {
    [[NSNotificationCenter defaultCenter] postNotificationName:GSDKUserCancelNoticationName object:nil];
}

- (void)textChangeAction {
    if (_unTextField.text.length > 0 && _pwTextField.text.length > 0) {
        _loginButton.selected = YES;
    } else {
        _loginButton.selected = NO;
    }
}

- (void)thirdPartyAction:(UIButton *)button {
    ThirdPartyLoginType type = (ThirdPartyLoginType)button.tag;
    if (_thirdPartyBlock) {
        _thirdPartyBlock(type);
    }
}

#pragma mark - UITextField Delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == _unTextField) {
        [_pwTextField becomeFirstResponder];
    } else {
        [_pwTextField resignFirstResponder];
        //登录
        [self loginAction];
    }
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField {
    if (textField == _unTextField) {
        _pwTextField.text = @"";
        _unTextField.text = @"";
    } else {
        _pwTextField.text = @"";
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [self hideError];
    [self hideHistoryView];
}

@end
